<template>
  <div class="app-container page-flex">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="业主单位" prop="ownerUnit">
              <el-input v-model="queryParams.ownerUnit" placeholder="请输入业主单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目区域" prop="projectRegion">
              <el-cascader v-model="queryParams.projectRegion" :options="searchRegionOptions"
                :props="{ lazy: true, lazyLoad: loadSearchRegion, value: 'value', label: 'label', checkStrictly: true }"
                placeholder="请选择项目区域" style="width: 240px" clearable />
            </el-form-item>
            <el-form-item label="执行总裁" prop="presidentsId">
              <el-select
                :model-value="selectedSearchPresident ? selectedSearchPresident.userName || selectedSearchPresident.nickName : ''"
                placeholder="请选择执行总裁" style="width: 240px" clearable @click="showSearchPresidentSelector = true"
                @clear="clearSearchPresident">
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchPresidentSelector = true"> 选择执行总裁 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="签订时间" prop="conSignTime" style="width: 308px">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label="合同状态" prop="contractStatus">
              <el-select v-model="queryParams.contractStatus" placeholder="请选择合同状态" style="width: 240px" clearable>
                <el-option v-for="item in contract_status" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="是否逾期" prop="isDelay">
              <el-select v-model="queryParams.isDelay" placeholder="请选择是否逾期" style="width: 240px" clearable>
                <el-option v-for="item in contract_is_delay" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item style="margin-left: auto">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="table-card">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <div style="display: flex; align-items: center; gap: 8px">
              <el-select v-model="sortField" placeholder="请选择排序字段" style="width: 170px" clearable
                @change="handleSortChange">
                <el-option label="合同名称" value="contractName" />
                <el-option label="合同编号" value="contractNumber" />
                <el-option label="业主单位" value="ownerUnit" />
                <el-option label="项目区域" value="projectRegion" />
                <el-option label="执行总裁" value="presidentsId" />
                <el-option label="合同签订时间" value="conSignTime" />
                <el-option label="合同约定完成时间" value="conEndTime" />
                <el-option label="合同是否有延期约定" value="hasExtension" />
                <el-option label="合同拆分状态" value="splitStatus" />
                <el-option label="是否逾期" value="isDelay" />
                <el-option label="审核状态" value="proStatus" />
              </el-select>
              <el-button v-if="sortField" :icon="sortOrder === 'asc' ? 'ArrowUp' : 'ArrowDown'" @click="toggleSortOrder"
                type="info" plain size="small" :title="sortOrder === 'asc' ? '当前为正序，点击切换为逆序' : '当前为逆序，点击切换为正序'">
                {{ sortOrder === 'asc' ? '正序' : '逆序' }}
              </el-button>
            </div>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="contractList" row-key="id" border height="100%" class="flex-table">
        <!-- 序号 -->
        <el-table-column label="序号" align="center" width="80">
          <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同名称" align="center" prop="contractName" show-overflow-tooltip />
        <el-table-column label="合同编号" align="center" prop="contractNumber" show-overflow-tooltip />
        <el-table-column label="业主单位" align="center" prop="ownerUnit" show-overflow-tooltip />
        <el-table-column label="项目区域" align="center" prop="projectRegionName" show-overflow-tooltip />
        <el-table-column label="执行总裁" align="center" prop="presidentsName" show-overflow-tooltip />
        <el-table-column label="合同签订时间" align="center" prop="conSignTime" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.conSignTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否有延期约定" align="center" prop="hasExtension" width="120">
          <template #default="scope">
            <dict-tag :options="contract_extension" :value="scope.row.hasExtension" />
          </template>
        </el-table-column>
        <el-table-column label="是否逾期" align="center" prop="isDelay" width="120">
          <template #default="scope">
            <dict-tag :options="contract_is_delay" :value="scope.row.isDelay" />
          </template>
        </el-table-column>
        <el-table-column label="合同状态" align="center" prop="contractStatus" width="120">
          <template #default="scope">
            <dict-tag :options="contract_status" :value="scope.row.contractStatus" />
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="proStatus" width="120">
          <template #default="scope">
            <dict-tag :options="approval_commit_status" :value="scope.row.proStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
          <template #default="scope">
            <el-tooltip content="审核" placement="top">
              <el-button link type="primary" icon="View" @click="handleAudit(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无审核数据" />
        </template>
      </el-table>

      <div class="pagination-container" v-show="total > 0">
        <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
          @pagination="getList" />
      </div>
    </el-card>

    <!-- 用户选择器对话框 -->
    <UserSelector v-model:visible="showSearchPresidentSelector" :multiple="false" title="选择执行总裁"
      @confirm="handleSearchPresidentConfirm" @cancel="handleSearchPresidentCancel" />
  </div>
</template>

<script setup name="ProAudit" lang="ts">
import { ref, reactive, toRefs, getCurrentInstance, onMounted } from 'vue';
import { getInfoAuditList } from '@/api/project/init/contract';
import { listAddressByParent } from '@/api/project/init/address';
import type { ProContractVO, ProContractQuery } from '@/api/project/init/contract/types';
import type { FormInstance } from 'element-plus';
import { parseTime } from '@/utils/ruoyi';
import { useRouter } from 'vue-router';
import UserSelector from '@/components/UserSelector/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const { approval_commit_status, contract_status, contract_is_delay, contract_extension } = toRefs<any>(
  proxy?.useDict('approval_commit_status', 'contract_status', 'contract_is_delay', 'contract_extension')
);

const contractList = ref<ProContractVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

// 搜索条件相关变量
const searchRegionOptions = ref([]);
const selectedSearchPresident = ref(null);
const selectedSearchPresidentName = ref('');
const showSearchPresidentSelector = ref(false);

// 排序相关
const sortField = ref<string | undefined>(undefined);
const sortOrder = ref<string>('asc'); // 设置默认为正序

const queryFormRef = ref<FormInstance>();

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractName: undefined,
    ownerUnit: undefined,
    presidentsId: undefined,
    projectRegion: undefined,
    contractStatus: undefined,
    isDelay: undefined,
    params: {}
  } as ProContractQuery
});

const { queryParams } = toRefs(data);

/** 格式化金额显示 */
const formatAmount = (amount) => {
  if (amount === null || amount === undefined) return '0.00';
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  });
};

/** 查询项目审核合同列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    // 使用工具类处理签订时间范围
    proxy?.addDateRange(params, dateRange.value, 'SignTime');
    // 处理项目区域参数
    if (params.projectRegion && Array.isArray(params.projectRegion)) {
      params.projectRegion = params.projectRegion.join(',');
    }
    // 处理排序参数
    if (sortField.value && sortOrder.value) {
      params.orderByColumn = sortField.value;
      params.isAsc = sortOrder.value;
    }
    const res = await getInfoAuditList(params);
    contractList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  // 重置搜索条件总裁选择
  selectedSearchPresident.value = null;
  selectedSearchPresidentName.value = '';
  // 重置排序条件
  sortField.value = undefined;
  sortOrder.value = 'asc';
  queryFormRef.value?.resetFields();
  queryParams.value.params = {};
  // 重置查询参数中的新字段
  queryParams.value.presidentsId = undefined;
  queryParams.value.projectRegion = undefined;
  handleQuery();
};

/** 审核按钮操作 */
const handleAudit = (row) => {
  router.push(`/project/pro-audit/index/${row.id}`);
};

// 处理排序变化
const handleSortChange = () => {
  // 如果选择了排序字段但没有选择排序顺序，则设置默认值
  if (sortField.value && !sortOrder.value) {
    sortOrder.value = 'asc';
  }
  handleQuery();
};

// 切换排序顺序
const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  handleQuery();
};

// 搜索条件区域数据加载
const loadSearchRegion = async (node, resolve) => {
  try {
    // 确保 parentId 是有效的数字，默认为 0
    let parentId = 0;
    if (node && typeof node.value === 'number') {
      parentId = node.value;
    } else if (node && node.value !== undefined && node.value !== null) {
      const parsed = parseInt(String(node.value), 10);
      if (!isNaN(parsed)) {
        parentId = parsed;
      }
    }

    const res = await listAddressByParent(parentId);
    const data = res.data || [];
    resolve(
      data.map((item) => ({
        value: item.id,
        label: item.name,
        leaf: false
      }))
    );
  } catch (error) {
    console.error('加载搜索区域数据失败:', error);
    resolve([]);
  }
};

// 处理搜索条件总裁选择确认
const handleSearchPresidentConfirm = (data) => {
  if (data.users && data.users.length > 0) {
    selectedSearchPresident.value = data.users[0];
    selectedSearchPresidentName.value = data.userNames || '';

    if (queryParams.value) {
      queryParams.value.presidentsId = data.userIds || '';
    }
  } else {
    selectedSearchPresident.value = null;
    selectedSearchPresidentName.value = '';
    if (queryParams.value) {
      queryParams.value.presidentsId = '';
    }
  }

  showSearchPresidentSelector.value = false;
};

// 取消搜索条件总裁选择
const handleSearchPresidentCancel = () => {
  showSearchPresidentSelector.value = false;
};

// 清空搜索条件总裁选择
const clearSearchPresident = () => {
  selectedSearchPresident.value = null;
  selectedSearchPresidentName.value = '';
  if (queryParams.value) {
    queryParams.value.presidentsId = '';
  }
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-flex {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 40px);
}

.table-card {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.table-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.flex-table {
  flex: 1;
}

.pagination-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 8px;
}
</style>
